<?php

class BaseCalc implements Calc {
    protected $a,
              $b,
              $operand;
    protected $dataOperations = array(
                    "+" => "sum",
                    "-" => "difference",
                    "*" => "multiply",
                    "/" => "division",
                    "%" => "percent",
                    "square" => "square",
                    "root" => "root",
                    "Clear" => "clearInput",
                    "=" => "equally",
                    "Back" => "clearLastOperand"
              );

    function getOperations() {
        return $this->dataOperations;
    }

    function calculate(&$data,$val) {

        if (!isset($data['numb'])) $data['numb'] = '';

        if (is_numeric($val)) {

            if (isset($data['numb2'])) {
                $data['numb2'] .= $val;
            } else {
                $data['numb'] .= $val;
                $this->a = $data['numb'];
            }
        } else {

            if (isset($data['numb2'])) {

                if ($val == 'Clear') {
                    $data = array();
                    return;
                }

                $this->a = $data['numb'];
                $this->b = $data['numb2'];
                $this->operand = $data['oper'];

                $result = $this->init();

                $data['oper'] = $val;
                $data['numb'] = $result;
                $data['numb2'] = '';

            } else {
                $data['oper'] = $val;
                $data['numb2'] = '';

                if ($val == 'Clear') {
                    $data = array();
                    return;
                }
            }
        }
    }

    function init() {
        foreach ($this->dataOperations as $k => $v) {
            if ($this->operand == $k) {
                return $this->$v($this->a,$this->b);
            }
        }
    }

    function sum($a,$b) {
        return $a + $b;
    }

    function difference($a,$b) {
        return $a - $b;
    }
    function multiply($a,$b) {
        return $a * $b;
    }
    function division($a,$b) {
        return $a / $b;
    }
    function percent($a,$b) {
        return ($this->a * $this->b) / 100;
    }
    final function clearInput() {

    }
    function clearLastOperand($a,$b='') {
        if (!empty($b)) {
            $this->b = substr($b,0,-1);
        } else {
            $this->a = substr($a,0,-1);
        }
    }

    final function equally($a) {
        return $a;
    }

    final function square($a,$b='') {
        return pow($a,2);
    }
    final function root($a,$b='') {
        return sqrt($a);
    }
}